/**
 * Copyright(c) 2013 Jade Techonologies Co., Ltd.
 *
 * History:
 *   13-7-5 下午3:39 Created by dwzhang
 */
package com.jade.framework.base.io;

import java.io.File;

import javax.annotation.PostConstruct;

import com.jade.framework.base.JadeSystem;

/**
 * 简单的文件存放集合。
 *
 * @author dwzhang
 * @version 1.0 13-7-5 下午3:39
 */
public class SimpleFileStore implements FileStore
{
    protected static final int MAX_DIR = 256;

    protected int dirCount = MAX_DIR;

    protected File path = null;

    protected File[] pool = null;

    private int next = 0;

    public void setPath(File path)
    {
        this.path = path;
    }

    public void setPath(String path)
    {
        this.path = new File(path);
    }

    public void setDirCount(int dirCount)
    {
        this.dirCount = dirCount;
    }

    @PostConstruct
    public void init()
    {
        if (path == null) {
            throw new IllegalArgumentException("No store path is set");
        }

        this.pool = new File[dirCount];
        for (int i = 0; i < dirCount; i++) {
            pool[i] = mkdirs(path, i);
        }
    }

    protected File mkdirs(File path, int i)
    {
        File file = new File(path, String.valueOf(i));
        if (!file.exists()) {
            file.mkdirs();
        }
        return file;
    }

    public File createDirectory()
    {
        return createDirectory(getFileName0(null));
    }

    public File createDirectory(String dirName)
    {
        File file = createFile(dirName);
        file.mkdirs();
        return file;
    }

    public File createFile()
    {
        return createFileByType("tmp");
    }

    public File createFileByType(String type)
    {
        return createFile(getFileName0(type));
    }

    public File createFile(String name)
    {
        int i = Math.abs(name.hashCode() % dirCount);
        return new File(pool[i], name);
    }

    private synchronized int nextIdentity()
    {
        next = (next + 1) & 0xFFF;
        return next;
    }

    private String getFileName0(String type)
    {
        StringBuilder sb = new StringBuilder();
        sb.append(System.currentTimeMillis());
        sb.append('.');
        sb.append(getJvmIdentity()).append('.');
        sb.append(nextIdentity());
        if (type != null) {
            sb.append('.');
            sb.append(type);
        }
        return sb.toString();
    }

    protected String getJvmIdentity()
    {
        return JadeSystem.getJvmIdentity();
    }
}
